package com.czxes.utils;

import com.czxes.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HtmlParseUtil {
  public List<Content> parseJD(String key) throws IOException {
      //获取请求
      String url="https://search.jd.com/Search?keyword="+key+"&enc=utf-8";

      Document document = Jsoup.parse(new URL(url), 30000);
      Element hotwords = document.getElementById("hotwords");
      Element element = document.getElementById("J_goodsList");
      Elements elements = element.getElementsByTag("li");
      ArrayList<Content> list = new ArrayList<>();
      // System.out.println(elements);
      for (Element el : elements) {
          String img = "https:"+el.getElementsByTag("img").eq(0).attr("src");
          String price = el.getElementsByClass("p-price").eq(0).text();
          String name = el.getElementsByClass("p-name").eq(0).text();
          String shop=el.getElementsByClass("curr-shop").text();
          String href = "https:"+el.getElementsByClass("p-img").select("a").attr("href");
          Content content = new Content();
          content.setImg(img);
          content.setPrice(price);
          content.setTitle(name);
          content.setShop(shop);
          content.setHref(href);
          list.add(content );
      }
        return list;
  }
}
